#!/usr/bin/python3
# coding: utf-8
# file: contextlib_.py
# 上下文管理
# 2018-06-20
import threading
from contextlib import contextmanager


class LockContext(object):

	def __init__(self):
		print('__init__')
		self.lock = threading.Lock()

	def __enter__(self):
		print('__enter__')
		self.lock.acquire()
		return self

	def __exit__(self, exc_type, exc_val, exc_tb):
		print('__exit__')
		self.lock.release()

with LockContext():
	print('In the context')


class OpenContext(object):

	def __init__(self, file, mode):
		self.fd = open(file, mode)

	def __enter__(self):
		return self.fd

	def __exit__(self, exc_type, exc_val, exc_tb):
		self.fd.close()

with OpenContext('test.txt', 'a') as f:
	f.write('aa')



@contextmanager
def make_open_context(file, mode):
	fp = open(file, mode)
	try:
		yield fp
	finally:
		fp.close()

with make_open_context('test.txt', 'a') as f:
	f.write('123')


@contextmanager
def make_context(*args):
	print(args)
	yield

with make_context(1, 2):
	with make_context(3, 4):
		print('In the context')